package com.mililoan.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class KeysUtil {
	private static char[]	HEX_DIGITS	= 
		{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E','F' };
	private static String	MD5			= "MD5";
	private static String	SHA			= "SHA";

	public static String MD5(String str) {
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance(MD5);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		md.reset();
		md.update(str.getBytes());

		byte[] bArray = md.digest();
		String finalStr = new String(encodeHex(bArray, HEX_DIGITS));
		// System.out.println("16位大写：" + finalStr.substring(8, 24));
		// System.out.println("32位大写：" + finalStr);
		return finalStr;
	}

	public static String SHA(String str) {
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance(SHA);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		md.reset();
		md.update(str.getBytes());
		byte[] bArray = md.digest();
		return new String(encodeHex(bArray, HEX_DIGITS));
	}
	
	// 随机生成5位随机数
	public final static String get5Radom() {
		String radomString = null;
		Random rand = new Random();
		// 产生0-9999的随机数
		int randNum = rand.nextInt(10000);
		radomString = String.valueOf(randNum);
		while (radomString.length() < 5) {
			radomString = "0" + radomString;
		}

		return radomString;
	}

	/**
	 * 
	 * @Title: encodeHex
	 * @Description: 二进制转16进制
	 * @author YangChaofeng 2016年9月8日 上午10:37:54
	 * @param data
	 * @param toDigits
	 * @return
	 */
	protected static char[] encodeHex(final byte[] data, final char[] toDigits) {
		final int len = data.length;
		final char[] out = new char[len << 1];
		for (int i = 0, j = 0; i < len; i++) {
			out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
			out[j++] = toDigits[0x0F & data[i]];
		}
		return out;
	}
}